package com.java110.mall.chain.partner.adapter.hibo.utils;


import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

public class MD5Utils {
    public MD5Utils() {
    }

    public static String getString(TreeMap<String, String> map) {
        List<String> keys = new ArrayList(map.keySet());
        StringBuilder prestr = new StringBuilder();

        for(int i = 0; i < keys.size(); ++i) {
            String key = (String)keys.get(i);
            String value = (String)map.get(key);
            if (i == keys.size() - 1) {
                prestr.append(key).append("=").append(value);
            } else {
                prestr.append(key).append("=").append(value).append("&");
            }
        }

        return prestr.toString();
    }

    public static TreeMap<String, Object> sortMapByKey(Map<String, Object> map) {
        if (map != null && !map.isEmpty()) {
            TreeMap<String, Object> sortMap = new TreeMap(new MapKeyComparator());
            sortMap.putAll(map);
            return sortMap;
        } else {
            return null;
        }
    }

    public static String md5Str(String text) throws Exception {
        byte[] bytes = text.getBytes(StandardCharsets.UTF_8);
        MessageDigest messageDigest = MessageDigest.getInstance("MD5");
        messageDigest.update(bytes);
        bytes = messageDigest.digest();
        StringBuilder sb = new StringBuilder();

        for(int i = 0; i < bytes.length; ++i) {
            if ((bytes[i] & 255) < 16) {
                sb.append("0");
            }

            sb.append(Long.toString((long)(bytes[i] & 255), 16));
        }

        return sb.toString();
    }
}